<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>贪吃蛇</title>
</head>
<style>
    canvas{
        margin:auto;
        /*border:1px solid;*/
        box-shadow: 0 0 10px #999;
    }
</style>
<body onload="draw()">
    <canvas id="canvas" height="400" width="600">
        浏览器不支持
    </canvas>

    <audio autoplay="autoplay" loop="loop" controls style="display: none">
        <source src="./img/m1.ogg" type="audio/ogg" />
        <source src="./img/m1.mp3" type="audio/mpeg" />
        您的浏览器 不支持此类播放
    </audio>
    <!-- <audio src="./img/m1.mp3" id="ms2"></audio> -->

    <!-- <button id="btn">开始</button> -->
</body>
</html>

<script>
    function draw(){
        var c = document.getElementById("canvas");
        var music = document.getElementById("ms2");
        var btn = document.getElementById("btn");
        // music.click()
        // music.play()
        if(!c.getContext){
            return
        }

        console.log('1111');
        var ctxt = c.getContext('2d');
        var isEatFood = true;
        var timer;
        // btn.onclick = function(){
        //     console.log("1111")
        //     ctxt.clearRect(0,0,canvas.width,canvas.height)
        // }
        // function clearCanvas(){
        //     console.log("1111")
        //     ctxt.clearRect(0,0,canvas.width,canvas.height)
        // }

        function Rect(x,y,width,height,color){
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.color = color;
        }
        Rect.prototype.draw = function(){
            ctxt.beginPath();
            ctxt.fillStyle = this.color;
            ctxt.fillRect(this.x,this.y,this.width,this.height);
            ctxt.strokeRect(this.x,this.y,this.width,this.height)
        };
        // var rect = new Rect(canvas.width/2-10,canvas.height/2-10,20,20,'red')
        // rect.draw()

        //创建蛇
        function Snake(){
        //    创建蛇头
            this.head = new Rect(canvas.width/10,canvas.height/10,20,20,'red');

        //    创建蛇身
            this.body = new Array();
            var x = this.head.x - 20;
            var y = this.head.y;
            for(var i = 0; i < 3; i ++){
                var rect = new Rect(x,y,20,20,'#999');
                this.body.push(rect);
                x -= 20
            }
            this.direction = 2
        }
        Snake.prototype.sDraw = function(){
            //绘制蛇头
            this.head.draw();
        //    绘制蛇身
            for(var i = 0; i < this.body.length; i ++){
                this.body[i].draw();
            }
        };
        Snake.prototype.move = function(){
            //加头
            var rect = new Rect(this.head.x,this.head.y,this.head.width,this.head.height,'#999')
            this.body.splice(0,0,rect);
            //去尾
            if(isEatFood == false){
                this.body.pop();
            }else{
                isEatFood = false
            }
            switch(this.direction){
                case 0:{
                    this.head.x -= this.head.width;
                    break;
                }
                case 1:{
                    this.head.y -= this.head.height;
                    break;
                }
                case 2:{
                    this.head.x += this.head.width;
                    break;
                }
                case 3:{
                    this.head.y += this.head.height;
                    break;
                }
            }
        //判断蛇头蛇身是否重叠
            for(var i = 0; i < this.body.length; i ++){
                if(isHit(this.head,this.body[i])){
                    clearInterval(timer);
                    timer = null;
                    alert("gameOver")
                }
            }
            //蛇头撞墙
            if(this.head.x>=canvas.width || this.head.x<0 ||
                this.head.y>=canvas.height || this.head.y<0){
                clearInterval(timer);
                timer = null;
                alert("gameOver")
            }

        };
        var snake = new Snake();
        snake.sDraw();

        var food = randForFood();
        function animate(){
            ctxt.clearRect(0,0,canvas.width,canvas.height);
            food.draw();
            snake.move();
            snake.sDraw();
            if(isHit(snake.head,food)){
                console.log('1111');
                isEatFood = true;
                food = randForFood();
            }
        }

        var btn = document.getElementById("btn");

        timer = setInterval(animate,200);
        // function onbegin(){
        //     timer = setInterval(animate,200);
        // }

        document.onkeydown = function(e){
            var ev = e || window.event;
            switch(ev.keyCode){
                case 37:{
                    snake.direction = 0;
                    snake.move();
                    break;
                }
                case 38:{
                    snake.direction = 1;
                    snake.move();
                    break;
                }
                case 39:{
                    snake.direction = 2;
                    snake.move();
                    break;
                }
                case 40:{
                    snake.direction = 3;
                    snake.move();
                    break;
                }
            }
        };

        function randForFood(){
            var isInSnake = true;
            while (isInSnake){
                //随机投放的位置
                var x = getRandoms(0,(canvas.width-20)/20)*20;
                var y = getRandoms(0,(canvas.height-20)/20)*20;
                //食物
                var rect = new Rect(x,y,20,20,'blue');
            //    判断食物是否与蛇头重叠
                if(isHit(snake.head,rect)){//是否与蛇头重叠
                    isInSnake = true;
                    continue;
                }
                isInSnake = false;

            //    判断食物是否与蛇身重叠
                for(var i = 0; i < snake.body.length; i ++){//是否与蛇身重叠
                    if(isHit(snake.body[i],rect)){
                        isInSnake = true;
                        break;
                    }
                }
            }
            return rect
        }

        //碰撞检测
        function isHit(rect1,rect2){
            var minX1 = rect1.x;
            var minX2 = rect2.x;
            var minY1 = rect1.y;
            var minY2 = rect2.y;

            var maxX1 = rect1.x + rect1.width;
            var maxX2 = rect2.x + rect2.width;
            var maxY1 = rect1.y+ rect1.height;
            var maxY2 = rect2.y+ rect2.height;

        //    判断矩形相交的最大和最小值
            var minX = Math.max(minX1,minX2);
            var minY = Math.max(minY1,minY2);
            var maxX = Math.min(maxX1,maxX2);
            var maxY = Math.min(maxY1,maxY2);
            if (minX < maxX && minY < maxY){
                return true;
            }else{
                return false
            }
        }
        //获取随机数
        function getRandoms(min,max){
            return Math.round(Math.random()*(max-min)+min)
        }


        /*
            贪吃蛇步骤
            1，画蛇
                蛇头，蛇身
            2，运动
                添加键盘事件
                   animate运动
            3，随机投放食物
                坐标位置
                食物是否投到蛇头蛇身上（数组重组）
            4，吃食物
                碰撞检测
                将食物添加到蛇身
            5，边缘检测
                碰撞检测
                蛇头是否碰到蛇身，边缘
         */

    }
</script>
